package com.dong.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * <h1>spring mvc 异步处理</h1>
 *
 * @author : dzj
 * @create: 2020-05-05 15:17
 */
@Controller
public class AsyncController {
    /**
     * 1. 控制器返回Callable
     * 2. spring异步处理, 将Callable提交到TaskExecutor 使用一个隔离的线程进行执行
     * 3. DispatcherServlet和所有的Filter 退出web容器线程,但是response保持打开
     * 4. Callable返回结果, SpringMVC将请求重新派发给容器, 恢复之前的处理
     * 5. 根据Callable返回的结果, SpringMVC继续进行视图渲染流程等(从收请求一直到视图渲染)...
     * @return
     */
    @ResponseBody
    @GetMapping("/async01")
    public Callable<String> async01() {
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "Callable<String> async01";
            }
        };
    }

    /**
     * 在set的时候会发生回调
     * @return
     */
    @GetMapping("/order")
    public DeferredResult<Object> createOrder() {
        DeferredResult result= new DeferredResult(3000L,"create fail");

        result.setResult("wancheng");
        return result;
    }
}
